package com.itheima.health.service.impl;

import com.itheima.health.dao.ReportDao;
import com.itheima.health.pojo.entity.ExportStatistical;
import com.itheima.health.pojo.entity.HotSetmeal;
import com.itheima.health.pojo.entity.Member;
import com.itheima.health.pojo.entity.Order;
import com.itheima.health.service.ReportServicer;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.temporal.TemporalAdjusters;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ReportServicerImpl implements ReportServicer {
    private ExportStatistical excelReport;

    @Autowired
    private ReportDao reportDao ;
    @Override
    public void exportBusinessReport(HttpServletResponse response) {
        excelReport=new ExportStatistical();

        //当前时间
        LocalDate now = LocalDate.now();
        excelReport.setOrderDate(now);

        //本周最早时间
        LocalDate startOfWeek = now.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
        LocalDate endOfWeek = now.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));

        //本月最晚时间
        YearMonth yearMonth = YearMonth.from(now);
        LocalDate startOfMonth = yearMonth.atDay(1);
        LocalDate endOfMonth = yearMonth.atEndOfMonth();


//        //会员数据统计
//        private Integer newMemberOfDay;   //当日新增会员数
        Integer newMemberOfDay = reportDao.getNewMemberOfDay(now);
        excelReport.setNewMemberOfDay(newMemberOfDay=(newMemberOfDay==null)?0:newMemberOfDay);


//        private Integer totalMember;//总会员数,
        Integer totalMember = reportDao.getNewMemberOfDay(null);
        excelReport.setTotalMember(totalMember=(totalMember==null)?0:totalMember);

//        private Integer totalMemberOfWeek;//本周会员数
        Integer totalMemberOfWeek = reportDao.getTotalMemberOfWeek(startOfWeek, endOfWeek);
        excelReport.setTotalMemberOfWeek(totalMemberOfWeek=(totalMemberOfWeek==null)?0:totalMemberOfWeek);


//        private Integer totalMemberOfMonth;//本月会员数

        Integer totalMemberOfMonth = reportDao.getTotalMemberOfMonth(startOfMonth, endOfMonth);
        excelReport.setTotalMemberOfMonth(totalMemberOfMonth=(totalMemberOfMonth==null)?0:totalMemberOfMonth);



//        //预约到诊数据统计
//        private Integer ReservationOfDay;//今日预约数
        Integer reservationOfDay = reportDao.getReservationOfDay(now);
        excelReport.setReservationOfDay(reservationOfDay=(reservationOfDay==null)?0:reservationOfDay);

//        private Integer DiagnosisCompletedOfDay;//今日到诊数
        Integer orders = reportDao.DiagnosisCompletedOfDay(now);
        excelReport.setDiagnosisCompletedOfDay(orders=(orders==null)?0:orders);


//        private Integer ReservationOfWeek;//本周预约数
        Integer reservationOfWeek = reportDao.getReservationOfWeek(startOfWeek, endOfWeek);
        excelReport.setReservationOfWeek(reservationOfWeek=(reservationOfWeek==null)?0:reservationOfWeek);


//        private Integer DiagnosisCompletedOfWeek;//本周到诊数
        Integer diagnosisCompletedOfWeek = reportDao.getDiagnosisCompletedOfWeek(startOfWeek, endOfWeek);
        excelReport.setDiagnosisCompletedOfWeek(diagnosisCompletedOfWeek=(diagnosisCompletedOfWeek==null)?0:diagnosisCompletedOfWeek);


//        private Integer ReservationOfMonth;//本月预约数
        Integer reservationOfMonth = reportDao.getReservationOfMonth(startOfMonth, endOfMonth);
        excelReport.setReservationOfMonth(reservationOfMonth=(reservationOfMonth==null)?0:reservationOfMonth);


//        private Integer DiagnosisCompletedOfMonth;//本月到诊数
        Integer diagnosisCompletedOfMonth = reportDao.getDiagnosisCompletedOfMonth(startOfMonth, endOfMonth);
        excelReport.setDiagnosisCompletedOfMonth(diagnosisCompletedOfMonth=(diagnosisCompletedOfMonth==null)?0:diagnosisCompletedOfMonth);


//
//
//        //热门套餐
//        private String setmealName;//套餐名称
//        private Integer setmealReservationNum;//预约数量
//        private Double proportion;//占比
//        private String remark;//备注

        //预约总数变量
        Integer setmealReservationSum=0;

        List<HotSetmeal> hotSetmeal = reportDao.getHotSetmeal();

        //统计预约数量
        for (HotSetmeal setmeal : hotSetmeal) {
            setmealReservationSum+=setmeal.getSetmealReservationNum();
        }

        //为每条数据算出占比
        for (HotSetmeal setmeal : hotSetmeal) {
            //setmeal.setProportion(setmeal.getSetmealReservationNum().doubleValue()/setmealReservationSum.doubleValue() );
            setmeal.setProportion(Double.valueOf(new DecimalFormat("#.00").format(setmeal.getSetmealReservationNum().doubleValue()/setmealReservationSum.doubleValue())));
        }


        excelReport.setHotSetmeal(hotSetmeal);

        //表格参数
        log.info("表格参数：{}",hotSetmeal);

        //使用POI导出数据
        reportDate(excelReport,response);
    }


    /**
     * 封装poi数据导出
     *
     * @param excelReport
     * @param response
     */
    private void reportDate( ExportStatistical excelReport, HttpServletResponse response) {




        //基于提供好的模板文件创建一个新的Excel表格对象
        try {

            ServletOutputStream os = response.getOutputStream();
            response.setHeader("Content-disposition", "attachment;filename=" + new String("report_template".getBytes(), "ISO8859-1") + ".xlsx");


            //加载模板
            //InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/report_template.xlsx");
            //基于提供好的模板文件创建一个新的Excel表格对象
            XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream(ResourceUtils.getFile("classpath:template/report_template.xlsx")));


            //获得Excel文件中的一个Sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            sheet.getRow(2).getCell(5).setCellValue(String.valueOf(excelReport.getOrderDate()));

            //会员数据统计
            //获取第5行
            XSSFRow row = sheet.getRow(4);
            log.info("4{}",String.valueOf(row.getCell(4)));
            row.getCell(5).setCellValue(excelReport.getNewMemberOfDay());
            log.info("5{}",String.valueOf(row.getCell(5)));
            row.getCell(7).setCellValue(excelReport.getTotalMember());
            log.info("7{}",String.valueOf(row.getCell(7)));

            //获取第6行
             row = sheet.getRow(5);
            log.info(String.valueOf(row.getCell(4)));
            row.getCell(5).setCellValue(excelReport.getTotalMemberOfWeek());
            row.getCell(7).setCellValue(excelReport.getTotalMemberOfMonth());



            //预约到诊数据统计
            //获取第8行
            row = sheet.getRow(7);
            log.info(String.valueOf(row.getCell(4)));
            row.getCell(5).setCellValue(excelReport.getReservationOfDay());
            row.getCell(7).setCellValue(excelReport.getDiagnosisCompletedOfDay());


            //获取第9行
            row = sheet.getRow(8);
            log.info(String.valueOf(row.getCell(4)));
            row.getCell(5).setCellValue(excelReport.getReservationOfWeek());
            row.getCell(7).setCellValue(excelReport.getDiagnosisCompletedOfWeek());

            //获取第10行
            row = sheet.getRow(9);
            log.info(String.valueOf(row.getCell(4)));
            row.getCell(5).setCellValue(excelReport.getReservationOfMonth());
            row.getCell(7).setCellValue(excelReport.getDiagnosisCompletedOfMonth());

            //热门套餐
            List<HotSetmeal> hotSetmeal = excelReport.getHotSetmeal();
            for (int i = 12; i < 16; i++) {
                HotSetmeal hs = hotSetmeal.get(i - 12);
                row = sheet.getRow(i);
                row.getCell(4).setCellValue(hs.getSetmealName());
                row.getCell(5).setCellValue(hs.getSetmealReservationNum());
                row.getCell(6).setCellValue(hs.getProportion());
                row.getCell(7).setCellValue(hs.getRemark());

            }

            //通过输出流将文件下载到客户端浏览器中
            //ServletOutputStream out = response.getOutputStream();
            excel.write(os);
            os.flush();
            os.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }


}
